<?php

/*
 *	Framework namespace
 */
namespace Nano
{
	/*
	 *	DSV class
	 *
	 *	I'm prefer own algoritm of saving/getting *.dsv
	 *	because default functions slower (?) and obsolete
	 *
	 *	@extends	\Nano\DSV
	 */
	class DSV extends \Kernel
	{
		/*
	 	 *	$extension	string	DSV file extension
		 */
		public $extension;
		
		/*
		 *	$file	string	File to work with
		 */
		public $file;
		
		/*
		 *	$delimiter	char	Field delimiter
		 */
		public $delimiter;
		
		/*
		 *	$enclosure	char	Enclosure character
		 */
		public $enclosure;
		
		/*
		 *	$escape	char	Escape character
		 */
		public $escape;
		
		/*
		 *	$regexp	string	DSV regexp string
		 */
		public $regexp = '/$s(?=(?:[^\$e]*\$e[^\$e]*\$e)*(?![^\$e]*\$e))/';
	
		/*
		 *	Export CSV file
		 *
		 *	@param	string	Pahth to file (without extension)
		 */
		public function import($file)
		{
			$this->file = $file.$this->extension;
			
			if(!Filesystem::exists($this->file))
			{
				throw new \Exception(__CLASS__.': CSV file "'.$this->file.'" does not exists');
			}
			
			$contents = Filesystem::get($this->file, true);
			$contents = explode("\n", $contents);
			$result = array();

			foreach($contents as $line)
			{
				if(!empty($line))
				{
					$result[] = $this->parse($line);
				}
			}
			
			return $result;
		}
		
		/*
		 *	Parse CSV line
		 *
		 *	@param	string	Line from CSV 
		 *	@return	array	Result rows
		 *
		 *	@private
		 */
		private function parse($line)
		{
			if(empty($line))
			{
				return false;
			}
			
			$enclosure = $this->enclosure;
			
			$delimiter = $this->delimiter;
			
			$regexp = str_replace(array('$s', '$e'), array($delimiter, $enclosure), $this->regexp);
			
			$line = preg_split($regexp, trim($line));
			
			$lambda = function($string) use ($enclosure)
			{
				return trim($string, $enclosure);
			};
			
			$line = array_map($lambda, $line);
			
			return $line;
		}
	}
}